"""测试数据处理"""
import os

from common.operateExcel import OperateExcel
from config import excel_title, DATADIR


class ProcessingTestData:
    def __init__(self):
        self.file = os.path.join(DATADIR, 'case.xlsx')
        self.excel_data = OperateExcel(self.file)
        self.sheetnames = self.excel_data.open_excel().sheetnames

    def get_data_list(self, sheetnames):
        """
        获取数据sheet页的数据，剔除被注释行的
        :param sheetnames: sheetname的列表，[sheetname1,sheetname2]形式
        :return: 数组，[{sheetname1：[{id:xx,keyword:xx,...},{id:xx,keyword:xx,...}]},{sheetname2：sheet内容}]形式
        """
        data_list = []
        if len(sheetnames) != 0:
            for sheetname in sheetnames:
                title = self.excel_data.get_sheet_title(sheetname)  # sheet页的首行
                # sheet页的首行在配置文件定义好的excel_title中
                isOK = True
                for i in title:
                    if i not in excel_title:
                        isOK = False
                        break
                if isOK:
                    data_dir = {}
                    cases = self.excel_data.read_excel(
                        sheetname)  # case---》[{id:xx,keyword:xx,...},{id:xx,keyword:xx,...}]
                    cases2 = []
                    for case in cases:
                        isOK_1, result_1 = self.excute_useless_case(case)  # 处理被注释的行
                        if isOK_1:
                            cases2.append(case)
                    data_dir[sheetname] = cases2
                    data_list.append(data_dir)
                else:
                    return False, "【sheet页获取】失败，【{}】中的首行字段【{}】没有在配置文件【{}】中定义，请检查用例。".format(sheetname, title,
                                                                                            excel_title)
            return True, data_list

        else:
            return False, "【sheet页获取】失败，没有获取到sheet名称【{}】，请检查用例。".format(sheetnames)

    def get_common_data(self):
        """
        公共用例数据（原始数据，剔除被注释行的）
        :return: [{sheetname1：[{id:xx,keyword:xx,...},{id:xx,keyword:xx,...}]},{sheetname2：sheet内容}]形式输出
        """
        common_sheet_name = []
        for sheet_name in self.sheetnames:
            if sheet_name.split("-")[0] == "common" or sheet_name.split("_")[0] == "common":
                common_sheet_name.append(sheet_name)
        isOK, common_case_list = self.get_data_list(common_sheet_name)
        return isOK, common_case_list

    def get_normal_data(self):
        """
        正常执行的用例数据（原始数据，剔除被注释行的）
        :return: [{sheetname1：[{id:xx,keyword:xx,...},{id:xx,keyword:xx,...}]},{sheetname2：sheet内容}]形式输出
        """
        normal_sheet_name = []
        for sheet_name in self.sheetnames:
            if sheet_name.split("-")[0] != "common" and sheet_name.split("_")[0] != "common" and sheet_name[
                0] is not '#':
                normal_sheet_name.append(sheet_name)
            else:
                continue
        isOK, normal_case_list = self.get_data_list(normal_sheet_name)
        return isOK, normal_case_list

    def get_useless_data(self):
        """
        被注释的用例
        :return:[{sheetname1：[{id:xx,keyword:xx,...},{id:xx,keyword:xx,...}]},{sheetname2：sheet内容}]形式输出
        """
        useless_sheet_name = []
        for sheet_name in self.sheetnames:
            if sheet_name[0] is '#':
                useless_sheet_name.append(sheet_name)
        isOK, useless_case_list = self.get_data_list(useless_sheet_name)
        return isOK, useless_case_list

    def excute_useless_case(self, case):
        """
        处理被注释的用例
        :param case:
        :return:
        """
        if str(case["id"]).__contains__("#"):
            return None, None
        else:
            return True, case

    def get_common_case(self, sheet_name):
        """
        获取xx公共用例中的用例
        :param sheet_name: 公共用例对应的sheet页名称
        :return: [{id:xx,keyword:xx,...},{id:xx,keyword:xx,...}]
        """
        isOK, result = self.get_common_data()  # result--->[{sheetname1：[{id:xx,keyword:xx,...},{id:xx,keyword:xx,...}]},{sheetname2：sheet内容}]
        if isOK:
            for data in result:
                cases = data.get(sheet_name)  # cases--->[{id:xx,keyword:xx,...},{id:xx,keyword:xx,...}]
                if cases is not None:
                    return True, cases
            if cases is None:
                return False, '找不到【{}】公共用例，请检查用例。'.format(sheet_name)
        else:
            return False, result

    def init_common_case(self, case):
        """通过用例行中调用的用例获取公共用例
        :param case: 正常执行的用例行 ：{id:xx,keyword:xx,...}
        :return:公共用例：[{id:xx,keyword:xx,...},{id:xx,keyword:xx,...}]
        """
        if case['keyword'] == '调用用例':
            sheet_name = case['locator']  # 公共用例对应的sheet页名称
            isOK, result = self.get_common_case(
                sheet_name)  # result --->[{id:xx,keyword:xx,...},{id:xx,keyword:xx,...}]

            if isOK and type([])==type(result):
                for i in result:  #这块有死循环问题
                    isOK_1, result_1 = self.init_common_case(i)  # 递归检查公共用例里是否存在调用用例
                    if isOK_1:
                        index = result.index(i)  # ‘调用用例’在数组中的下标
                        for j in result_1:
                            result.insert(index + 1, j)  # 在‘调用用例’后追加数据
                            index += 1
                    elif isOK_1 == None:
                        continue
                    else:
                        return isOK_1, result_1

            return isOK, result
        else:
            return None, None

    def combined_cases(self):
        """
        组合测试用例
        :return:[{sheetname1：sheet内容},{sheetname2：sheet内容}]形式输出
        """
        n_isOK, nomal_data = self.get_normal_data()
        c_isOK, common_data = self.get_common_data()

        common_case_list = []
        if c_isOK:
            common_case_list = [k for k, v in common_data.items()]

        combined_cases = {}
        for key, value in nomal_data.items():
            c = []
            for case in value:
                isOK, result = self.excute_useless_case(case)  # 看数据是否被注释，True为不被注释的
                if isOK:
                    c.append(result)
                    # 如果为调用用例的行，把公共用例插入进去
                    if result["keyword"] == "调用用例":
                        sheetname = result["locator"]
                        if sheetname in common_case_list:
                            print("【调用公共用例】【{}】开始".format(sheetname))
                            common_case = common_data[sheetname]
                            for i in common_case:
                                c.append(i)
                            print("【调用公共用例】【{}】结束".format(sheetname))

                        else:
                            return False, "【调用公共用例】失败：不存在【{}】公共用例。".format(sheetname)
                else:
                    print(result)
            combined_cases[key] = c

        return True, combined_cases

# print(os.path.join(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),'data'), 'case.xlsx'))


#
# def open_excel(file):
#     """打开excel"""
#     wb = openpyxl.load_workbook(file)
#     return wb
#
#
# def get_sheetnammes(file):
#     wb = open_excel(file)
#     sheetnames = wb.sheetnames
#     return sheetnames
#
#
# def open_sheet(file, sheet):
#     wb = open_excel(file)
#     sh = wb.get_sheet_by_name(sheet)
#     return sh
#
#
# def read_excel(file, sheet):
#     """读excel的数据"""
#     sh = open_sheet(file, sheet)
#     datas = list(sh.rows)  # excel中全部的数据
#     title = [i.value for i in datas[0]]  # excel中的首行数据
#     cases = []
#     for i in datas[1:]:
#         data = [k.value for k in i]
#         case = dict(zip(title, data))
#
#         common_sheet = get_common_case_name(case)
#
#         if common_sheet == '' or common_sheet is None:
#             cases.append(case)
#         else:
#             common_cases = read_excel(file, common_sheet)
#             for common_case in common_cases:
#                 cases.append(common_case)
#     return cases
